<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus'
import type { LoginPwdReq } from '@/apis/common/loginApi'
import { reactive, ref } from 'vue'
import { loginApi } from '@/apis/common/loginApi'

const emits = defineEmits(['success'])

const formData = ref<Partial<LoginPwdReq>>({ loginType: 'SMS' })
const formRef = ref<FormInstance>()
const formRules = reactive<FormRules<LoginPwdReq>>({
  loginName: [{ required: true, message: '请输入手机号码', trigger: 'blur' }],
  authCode: [{ required: true, message: '请输入密码', trigger: 'blur' }],
})
const loading = ref(false)

function onSubmit() {
  formRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      loading.value = true
      try {
        const data = await loginApi.login(formData.value)
        emits('success', data)
      }
      finally {
        loading.value = false
      }
    }
  })
}

const countdown = ref(0)
function sendLoginSms() {
  formRef.value?.validateField('loginName', async (valid: boolean) => {
    if (valid && formData.value.loginName) {
      startCountdown(30)
      await loginApi.sendCaptcha({ type: 'SMS_LOGIN', target: formData.value.loginName })
      ElMessage.success('短信已发送')
    }
  })
}

/**
 *
 * @param time 开始倒计时
 */
function startCountdown(time: number) {
  countdown.value = time
  if (time <= 0) {
    return
  }
  setTimeout(() => {
    startCountdown(time - 1)
  }, 1000)
}
</script>

<template>
  <el-form
    ref="formRef"
    :model="formData"
    :rules="formRules"
    label-position="right"

    scroll-to-error hide-required-asterisk
    size="large"
    @submit.prevent
  >
    <el-form-item prop="loginName">
      <el-input
        v-model="formData.loginName"
        placeholder="手机号码"
      >
        <template #prepend>
          +86
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="authCode">
      <el-input
        v-model="formData.authCode"
        placeholder="手机验证码"
      >
        <template #append>
          <el-button v-if="countdown <= 0" @click="sendLoginSms">
            获取验证码
          </el-button>
          <template v-else>
            重新获取({{ countdown }}秒)
          </template>
        </template>
      </el-input>
    </el-form-item>

    <el-form-item class="w-full">
      <el-button
        type="primary"
        class="w-full"
        native-type="submit"
        @click="onSubmit"
      >
        登录
      </el-button>
    </el-form-item>
  </el-form>
</template>
